package org.hagen.mmia.yars.collection;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
import java.util.TreeMap;

import org.apache.lucene.index.Term;
import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.hagen.mmia.yars.engine.Index;

public class Collection {

	public static Map<String,Document>	documents = new TreeMap<String,Document>();
	public static ArrayList<Topic>		   topics = new ArrayList<Topic>();	
	
	private static IndexSearcher __searcher = null;
	
	Collection() {
	}

	static public void addTopic( Topic topic ) {
		topics.add( topic );
	}
	
	static public Topic getTopicByID( String ID ) {
		for( Topic topic : topics ) {
			if( topic.ID.equals(ID) ) {
				return topic;
			}
		}
		return null;
	}

	static public Topic getTopicByIndex( int index ) {
		if( index > topics.size()-1 ) {
			return null;
		}
		
		return topics.get( index );
	}
	
	static public Document getDocument( String docID ) {
		
		Document result = documents.get( docID );
		
		if( result == null ) {
			
			// access the document content from index
			if( __searcher == null ) {
				__searcher = new IndexSearcher( Index.getReader() );				
			}
			
			BooleanQuery bq = new BooleanQuery();
			bq.add(new TermQuery(new Term( Index.FIELD_ID, docID)), Occur.MUST);
			
			try {
				TopDocs hits = __searcher.search( bq, 1 );

				if( hits.totalHits == 1 ) {
					int 		index = hits.scoreDocs[0].doc;
					Document	netDoc = new Document( index, docID );
					
					documents.put( docID, netDoc );
					
					return netDoc;
				}
				
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}
		
		return result;
	}

	public static org.apache.lucene.document.Document getDocument(int i) throws IOException {
		
		return Index.getReader().document( i );
	}
}
